//
//  JCLComposeView.swift
//  WeiBo
//
//  Created by DDC on 2017/9/21.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit
import pop
class JCLComposeView: UIView {
    
    /// 设置闭包 传递
    fileprivate var completionBlock:((_ clsName: String?)->())?
    /// 数据模型
    let composeList = [["imageName":"tabbar_compose_book","title":"阅读","clsName":"JCLTestViewController"],
                       ["imageName":"tabbar_compose_camera","title":"相机"],
                       ["imageName":"tabbar_compose_delete","title":"回收站"],
                       ["imageName":"tabbar_compose_envelope","title":"飞信"],
                       ["imageName":"tabbar_compose_friend","title":"朋友圈"],
                       ["imageName":"tabbar_compose_more","title":"更多","actionName":"clickMore"],
                       ["imageName":"tabbar_compose_transfer","title":"金币"],
                       ["imageName":"tabbar_compose_video","title":"视频"],
                       ["imageName":"tabbar_compose_wbcamera","title":"发现"],
                       ["imageName":"tabbar_compose_weibo","title":"心情"]]
    /// scrollView
    @IBOutlet weak var scrollView: UIScrollView!
    /// 返回按钮
    @IBOutlet weak var backButton: UIButton!
    /// 返回按钮中间x的约束
    @IBOutlet weak var backBtnCenterXCons: NSLayoutConstraint!
    /// 关闭按钮中的x的约束
    @IBOutlet weak var closeBtnCenterXCons: NSLayoutConstraint!
    /// 类方法创建界面
    class func composeView() -> JCLComposeView {
        let nib = UINib(nibName: "JCLComposeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! JCLComposeView
        
        v.frame = UIScreen.main.bounds
        
        v.setupUI()
        
        return v
    }
    /// 展现界面
    func show(completion:@escaping ( _ clsName:String?)->()) {
        
        
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        completionBlock = completion
        vc.view .addSubview(self)
        //显示当前进入的动画
        showCurrentAnimation()
    }
    
    /// 移除compeseView界面
    @IBAction func closeCompose() {
        
       showButtonDownAnimation()
    
    }
    /// 返回按钮点击事件
    @IBAction func backBtnClick() {
        /// 设置偏移动画
        scrollView.setContentOffset(CGPoint(x:0,y:0), animated: true)
        /// 还原约束
        backBtnCenterXCons.constant = 0
        closeBtnCenterXCons.constant = 0
        /// 开始动画
        UIView.animate(withDuration: 0.25, animations: { 
            self.layoutIfNeeded()
            self.backButton.alpha = 0
        }) { (_) in
         
            self.backButton.alpha = 1
            self.backButton.isHidden = true
        }
        
    }

}

extension JCLComposeView {
    
    func setupUI () {
        
        layoutIfNeeded()
        
        let rect = scrollView.bounds
        let width = scrollView.bounds.width
        // 创建按钮视图
        for i in 0..<2 {
            
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i) * width, dy: 0))
            addButtons(v: v, idx: i * 6)
            scrollView.addSubview(v)
        }
        
        scrollView.contentSize = CGSize(width: 2 * width, height: 0)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = true
        
    }
    /// 添加撰写页面按钮
    ///
    /// - Parameters:
    ///   - v: 添加到的界面
    ///   - idx: 索引
    func addButtons(v:UIView ,idx:Int) {
        
        let count = 6
        
        for i in idx..<(idx+count) {
            
            /// 如果超过临界值  跳出循环
            if i  >= composeList.count {
                break
            }
            let dict = composeList[i]
            
            guard let imageName = dict["imageName"],
                let title = dict["title"] else {
                    return
            }
            /// 创建按钮
            let button = JCLComposeTypeButton.createComposeButton(imageName: imageName, title: title)
            /// 根据字典内容来判断是否有点击事件
            if let actionName = dict["actionName"] {
                /// Selector(string) == OC:NSStringFromClass(@"string")
                button.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            } else {
                button.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
            }
            button.clsName = dict["clsName"]
            /// 添加到界面上
            v.addSubview(button)
            
        }
        /// 利用九宫格来创建布局按钮
        for (i,btn) in v.subviews.enumerated() {
            // 按钮尺寸
            let btnSize = CGSize(width: 100, height: 100)
            // 间距
            let margin = (v.bounds.width - 3 * btnSize.width) / 4
            // x
            let col = i % 3
            let x = (CGFloat(col) + 1)*margin + CGFloat(col) * btnSize.width
            // y 
            let y:CGFloat = (i > 2) ? v.bounds.height - btnSize.height : 0
            
            btn.frame = CGRect(x: x, y: y, width: btnSize.width, height: btnSize.height)
            
        }
        
    }
    
    /// FIXME
    /// 此处的坑---> 在XIB创建button界面显示的时候,尽量使用empty,如果使用view的话 要更改它的自动布局四周的约束,因为它是默认带上的,会致使按钮无法响应点击事件
    @objc func clickButton (selectedBtn:JCLComposeTypeButton) {
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        for (i,btn) in v.subviews.enumerated() {
            
            // 缩放动画
            let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            let scale = (selectedBtn == btn) ? 2 : 0.5
            anim.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            anim.duration = 0.5
            btn.pop_add(anim, forKey: nil)
            
            // 渐变动画
            let alphaAnim :POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnim.toValue = 0.2
            alphaAnim.duration = 0.5
            btn.pop_add(alphaAnim, forKey: nil)
            
            // 动画完毕执行回调
            if i == 0 {
                alphaAnim.completionBlock = { _,_ in
                
                    print("执行回调")
                    self.completionBlock?(selectedBtn.clsName)
                }
            
            }
        }
    }
    
    
    /// 更多按钮点击事件
    @objc func clickMore() {
        print("clickMore")
        
        let offsetPoint = CGPoint(x: scrollView.bounds.width, y: 0)
        scrollView.setContentOffset(offsetPoint, animated: true)
        /// 显示返回按钮
        backButton.isHidden = false
        /// 设置约束
        backBtnCenterXCons.constant -= 100
        closeBtnCenterXCons.constant += 100
        /// 设置动画
        UIView.animate(withDuration: 0.25) { 
            self.layoutIfNeeded()
        }
        
    }
}

// MARK: - 撰写按钮点击动画
extension JCLComposeView {
    fileprivate func showCurrentAnimation() {
        
        let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.fromValue = 0
        anim.toValue = 1
        anim.duration = 0.25
        
        pop_add(anim, forKey: nil)
        
        showButtonUpAnimation()

    }
    
    /// 按钮动画向上
    fileprivate func showButtonUpAnimation() {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        let v  = scrollView.subviews[page]
        
        for (i,btn) in v.subviews.enumerated() {
            
            let anim:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim.fromValue = btn.center.y + 400
            anim.toValue  = btn.center.y
            anim.springBounciness = 10
            anim.springSpeed = 8
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            btn.layer.pop_add(anim, forKey: nil)
        }
        
        
    }
    
    /// 按钮动画向下
    fileprivate func showButtonDownAnimation() {
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        for(i,btn) in v.subviews.enumerated().reversed() {
            
            let anim:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + 400
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            btn.layer.pop_add(anim, forKey: nil)
            
            if i == 0 {
                // 最后一个按钮落下之后
                anim.completionBlock = {_,_ in
                    
                    self.hideComposeView()
                }
            }
        }
    }
    
    fileprivate func hideComposeView () {
        
        let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.toValue = 0
        anim.fromValue = 1
        anim.duration = 0.25
        pop_add(anim, forKey: nil)
        
        /// 动画完成之后,移除撰写页面
        anim.completionBlock = { _,_ in
            
            self.removeFromSuperview()
        }
        
    }
    
}
